<template>
  <Page :title="navTitle">
    <template #navBarCustom>
      <div class="flex items-center navBox">
        <div class="back" @click="back">
          <img class="icon" src="static/icons/back.png" mode="" />
          <span style="color: #fff">{{ navTitle }}</span>
        </div>
        <div class="nav-bar-btns flex" style="margin-left: auto">
          <div class="item flex items-center"  @click="submit()">
            <img class="icon mt-2px mr-4px" src="static/icons/scantron-submit.png" mode="" />
            <span class="name text-white">提交</span>
          </div>
        </div>
      </div>
    </template>
    <template #content>
      <div class="w-full h-full p-20px box-border">
        <div
          class="container w-full h-full flex flex-col bg-white text-333 p-20px box-border overflow-scroll"
        >
          <!-- 作业内容 -->
          <div class="task mb-20px">
            <div class="module-item flex items-center">
              <div class="rect mr-6px"></div>
              <div class="title font-bold">作业内容</div>
            </div>
            <div class="content">{{ stem }}</div>
          </div>
          <!-- 图片说明 -->
          <div class="task mb-20px">
            <div class="module-item flex items-center">
              <div class="rect mr-6px"></div>
              <div class="title font-bold">图片说明</div>
            </div>
            <div class="content img-content">
              <el-image
                v-for="(img, imgIndex) in showImgs"
                :key="img"
                :src="img"
                fit="contain"
                class="img-item"
                :preview-src-list="showImgs"
                :initial-index="imgIndex"
              />
            </div>
          </div>
          <!-- 我的作答 -->
          <div class="answer mb-20px">
            <div class="module-item flex items-center">
              <div class="rect mr-6px"></div>
              <div class="title font-bold">我的作答</div>
            </div>
            <div class="content" style="width: 8rem; margin-top: 0.14rem">
              <el-input
                type="textarea"
                :rows="5"
                :maxlength="200"
                :show-word-limit="true"
                resize="none"
                placeholder="请输入"
                v-model="form.answer"
                style="font-size: 0.2rem"
              >
              </el-input>
            </div>
          </div>
          <!-- 上传图片或视频 -->
          <div class="upload-wrap mt-10px">
            <div class="list-wrap">
              <div
                class="inline-block relative"
                v-for="(file, index) in form.fileList"
                :key="index"
                @click="openFile(file)"
              >
                <!-- 图片 -->
                <div class="item" v-if="file.type === 'photo'">
                  <el-image class="photo" :src="file.fileUrl" :preview-src-list="[file.fileUrl]" />
                </div>
                <!-- 视频 -->
                <div class="item" v-else-if="file.type === 'video'">
                  <VideoPreviewer :src="file.fileUrl" />
                </div>
                <!-- 其它 -->
                <div class="item" v-else>
                  <el-image class="other" :src="file.icon" />
                </div>
                <img
                  class="delete absolute"
                  src="static/icons/close-warning.png"
                  :data-index="index"
                  @click.stop="deleteFile"
                />
              </div>
              <el-popover
                placement="right"
                width="100"
                trigger="manual"
                v-model="isShowUploadPopover"
              >
                <div class="flex flex-col items-center justify-between" style="height: 1.05rem">
                  <CustomButton
                    class="block"
                    style="width: 1.4rem; height: 0.47rem"
                    @click="upload('photo')"
                  >
                    图片
                  </CustomButton>
                  <CustomButton
                    class="block"
                    style="width: 1.4rem; height: 0.47rem"
                    @click="upload('video')"
                  >
                    视频
                  </CustomButton>
                </div>
                <img
                  slot="reference"
                  style="height: 1.31rem"
                  src="static/icons/camera-gray.png"
                  @click.stop="isShowUploadPopover = !isShowUploadPopover"
                />
              </el-popover>
            </div>
          </div>
          <!-- 上传文件提示 -->
          <div class="upload-tips text-F8AC23 mt-10px">*单个视频最长5分钟</div>
        </div>
      </div>
    </template>
  </Page>
</template>

<script>
import { mapState, mapGetters } from 'vuex'
import Page from '@/components/page/newPage'
import CustomButton from '@/components/button'
import VideoPreviewer from '@/components/video/previewer'
import { creatEexceptionAnalysisApi } from '@/api/common'
import { upExamQuestionAnswerApi } from '@/api/homework'
import { uploadImage, getFileSuffix } from '@/utils'
import ppt from '@/assets/learning/ppt.png'
import xlsx from '@/assets/learning/xlsx.png'
import pdf from '@/assets/learning/pdf.png'
import photo from '@/assets/learning/photo.png'
import video from '@/assets/learning/vedio.png'
import word from '@/assets/learning/word.png'
import audio from '@/assets/learning/audio.png'
import other from '@/assets/learning/other.png'
import axios from 'axios'

const fileTypes = [
  {
    type: 'ppt',
    icon: ppt, // ppt
    suffixes: ['pptx', 'ppt']
  },
  {
    type: 'xlsx',
    icon: xlsx, // 表格
    suffixes: ['xlsx', 'xls', 'csv']
  },
  {
    type: 'pdf',
    icon: pdf, // pdf
    suffixes: ['pdf']
  },
  {
    type: 'photo',
    icon: photo, // 图片
    suffixes: ['bmp', 'jpg', 'jpeg', 'png', 'gif']
  },
  {
    type: 'video',
    icon: video, // 视频
    suffixes: ['avi', 'wmv', 'mpg', 'mpeg', 'mov', 'rm', 'ram', 'swf', 'flv', 'mp4']
  },
  {
    type: 'word',
    icon: word, // 文档
    suffixes: ['txt', 'doc', 'docx']
  },
  {
    type: 'audio',
    icon: audio, // 音频
    suffixes: ['mp3', 'wav', 'wma', 'mp2', 'flac', 'midi', 'ra', 'ape', 'aac', 'cda', 'm4a']
  }
]

export default {
  components: {
    Page,
    CustomButton,
    VideoPreviewer
  },
  directives: {},
  beforeRouteLeave(to, from, next) {
    if (this.canBack) {
      next()
    } else {
      window.history.pushState(null, null, location.pathname + '#/pages/homework/todo/task/index')
      this.$popup.show({
        type: 'confirm',
        success: (popup) => {
          popup.$on('cancel', () => {
            this.$popup.hide('confirm')
          })
          popup.$on('confirm', () => {
            this.$popup.hide('confirm')

            // 保存进度
            const { answer: studentAnswer, fileList } = this.form
            const studentAnswerFiles = fileList.map((file) => {
              const { fileName, fileUrl, type } = file

              switch (type) {
                case 'photo':
                  return {
                    fileName,
                    fileBase64Data: fileUrl.replace('data:image/png;base64,', '')
                  }
                default:
                  return {
                    fileName,
                    fileUrl
                  }
              }
            })
            const { localStudentAnswer: formdata } = this.currentQuestion
            formdata.studentAnswer = studentAnswer
            formdata.studentAnswerFiles = studentAnswerFiles

            this.$nextTick(() => {
              this.canBack = true
              this.$router.back()
            })
          })
          popup.setData({
            title: '确认退出？',
            content: '本次进度将保存',
            cancelText: '取消',
            confirmText: '退出'
          })
        }
      })
    }
  },
  data() {
    return {
      showImgs: [],
      canBack: false,
      appDom: document.getElementById('app'),
      // 累计时间
      cumulativeTime: {
        vm: this._self,
        timeout: null,
        value: 0, // 单位：秒
        // 累加
        run: function () {
          this.timeout = setTimeout(() => {
            const beginTime = this.vm.currentHomework.record.beginTime
            const endTime = this.vm.currentHomework.record.endTime

            if (beginTime && endTime) {
              const endTimestamp = new Date(endTime).getTime()
              const nowTime = new Date().getTime()
              if (nowTime >= endTimestamp) {
                this.vm.submit(true)
                this.vm.$popup.hideAll() // 如果存在弹窗，关闭
                this.vm.$popup.show({
                  type: 'alert',
                  success: (popup) => {
                    popup.$on('confirm', () => {
                      this.vm.$popup.hide('alert')
                    })
                    popup.setData({
                      content: '已超过作答时间，作业已自动提交'
                    })
                  }
                })
                return
              }
            }

            this.value++
            this.run()
          }, 1000)
        },
        reset: function () {
          clearTimeout(this.timeout)
          this.value = 0
        }
      },
      isShowUploadPopover: false,
      form: {
        answer: '', // 我的作答
        fileList: [] // 作答图片或视频
      }
    }
  },
  computed: {
    ...mapState(['homework']),
    ...mapGetters(['studentId']),
    currentHomework() {
      return this.homework.currentHomework
    },
    currentQuestion() {
      const { questions, questionIndex } = this.currentHomework
      return questions[questionIndex]
    },
    stem() {
      return this.currentQuestion.stem
    },
    navTitle() {
      const {
        record: { examName }
      } = this.currentHomework

      return examName
    }
  },
  watch: {
    currentHomework: {
      handler(newVal, oldVal) {
        const {
          record: { id }
        } = newVal

        this.$storage.homework.putCacheItem({
          id,
          value: newVal
        })
      },
      immediate: false,
      deep: true
    }
  },
  created() {
    this.init()
    this.getImages()
  },
  mounted() {
    this.cumulativeTime.run()
    this.appDom.addEventListener('click', this.handleHideUploadPopover)
  },
  beforeDestroy() {
    this.cumulativeTime.reset()
    this.appDom.removeEventListener('click', this.handleHideUploadPopover)
  },
  methods: {
    back() {
     this.$router.back()
    },
    init() {
      const {
        localStudentAnswer: { studentAnswer, studentAnswerFiles }
      } = this.currentQuestion

      const fileListTemp = studentAnswerFiles.map((file) => {
        const { fileName, fileBase64Data, fileUrl } = file
        if (fileBase64Data) {
          // 图片
          return {
            fileName,
            fileUrl: `data:image/png;base64,${fileBase64Data}`,
            icon: photo,
            type: 'photo'
          }
        } else {
          // 其他文件
          const suffix = getFileSuffix(fileUrl)
          const fileType = fileTypes.find((item) => {
            if (item.suffixes.indexOf(suffix) != -1) {
              return true
            } else {
              return false
            }
          })
          const { icon, type } = fileType ? fileType : { icon: other, type: 'other' }
          return {
            fileName,
            fileUrl,
            icon,
            type
          }
        }
      })

      this.form.answer = studentAnswer
      this.form.fileList.push(...fileListTemp)
    },
    getImages(){
      let that = this
      const {
        record: {additionalDataUrl}
      } = this.currentHomework
      if(additionalDataUrl){
        axios({
          method: 'get',
          url: additionalDataUrl,
          responseType: 'json'
        }).then(res => {
          let data = res.data
          if (data) {
            that.showImgs = data['showImgs']
          }
        })
      }
    },
    async upload(type) {
      this.handleHideUploadPopover()

      const { fileList } = this.form
      if (fileList.length === 10) {
        this.$message.info('最多上传10张照片或视频')
        return
      }

      switch (type) {
        case 'photo':
          {
            const { android_call } = window

            if (!android_call) {
              const base64 = await uploadImage()
              fileList.push({
                fileName: `picture-${Date.now()}.png`,
                fileUrl: base64,
                icon: photo,
                type: 'photo'
              })
            } else {
              const callback = (base64) => {
                fileList.push({
                  fileName: `picture-${Date.now()}.png`,
                  fileUrl: `data:image/png;base64,${base64}`,
                  icon: photo,
                  type: 'photo'
                })
                this.$message.success('上传成功！')
              }

              const callBackName = `fn${new Date().getTime()}`
              window.android_call[callBackName] = callback.bind(this)

              android.takePhoto(callBackName)
            }
          }
          break
        case 'video':
          {
            const { android_call } = window

            if (android_call) {
              const {
                record: { id: examId }
              } = this.currentHomework
              const { questionId } = this.currentQuestion

              const callback = (fileUrl) => {
                const suffix = getFileSuffix(fileUrl)
                const fileType = fileTypes.find((item) => {
                  if (item.suffixes.indexOf(suffix) != -1) {
                    return true
                  } else {
                    return false
                  }
                })

                const { icon, type } = fileType ? fileType : { icon: other, type: 'other' }

                fileList.push({
                  fileName: `video-${Date.now()}.${suffix}`,
                  fileUrl,
                  icon,
                  type
                })
                this.$message.success('上传成功！')
              }

              const callBackName = `fn${new Date().getTime()}`
              window.android_call[callBackName] = callback.bind(this)

              android.shootVideo(examId, questionId, callBackName)
            }
          }
          break
        default:
          break
      }
    },
    deleteFile(e) {
      const { fileList } = this.form
      const { index } = e.target.dataset
      fileList.splice(parseInt(index), 1)
    },
    handleHideUploadPopover() {
      this.isShowUploadPopover = false
    },
    openFile(file) {
      const { android, android_call } = window
      const { fileName, fileUrl, type } = file

      switch (type) {
        case 'photo':
          break
        case 'video':
          if (android && android_call) {
            const onEnded = () => {}
            const callBackName = `fn${new Date().getTime()}`
            android_call[callBackName] = onEnded.bind(this)
            android.openVideo(fileUrl, fileName, callBackName)
          }
          break
        default:
          // other
          if (android && android_call) {
            const callback = () => {}
            const callBackName = `fn${new Date().getTime()}`
            window.android_call[callBackName] = callback.bind(this)
            android.openFile(fileUrl, fileName, callBackName)
          }
          break
      }
    },
    submit(force = false) {
      const _submit = async () => {
        const {
          record: { id }
        } = this.currentHomework
        const { answer: studentAnswer, fileList } = this.form
        const studentAnswerFiles = fileList.map((file) => {
          const { fileName, fileUrl, type } = file

          switch (type) {
            case 'photo':
              return {
                fileName,
                fileBase64Data: fileUrl.replace('data:image/png;base64,', '')
              }
            default:
              return {
                fileName,
                fileUrl
              }
          }
        })
        const { localStudentAnswer: formdata } = this.currentQuestion
        formdata.studentAnswer = studentAnswer
        formdata.studentAnswerFiles = studentAnswerFiles

        await upExamQuestionAnswerApi(formdata)
        // 如果单道题做题时间不足10秒，创建异常分析
        if (formdata.studentDuration < 10) {
          const {
            record: { examCode = '', examName, subject, createTime }
          } = this.currentHomework
          // 只上传作业异常分析
          if (!examCode) {
            await creatEexceptionAnalysisApi({
              type: '1',
              exceptionDay: this.$utils.parseTime(createTime, '{y}-{m}-{d}'),
              title: examName,
              subject
            })
          }
        }

        this.$message.success('提交成功')
        this.$route.params.completed = true
        this.canBack = true
        this.$router.back()
        this.$nextTick(() => this.$storage.homework.deleteCacheItem(id))
      }

      const { android } = window
      if (android) {
        android.stopVideo() // 如果正在录像，停止录像并返回
      }

      if (force) {
        // 强制提交
        const { localStudentAnswer: formdata } = this.currentQuestion
        formdata.studentDuration = this.cumulativeTime.value // 更新做题时间
        this.cumulativeTime.reset() // 停止计时
        this.$nextTick(() => _submit())
      } else {
        this.$popup.show({
          type: 'confirm',
          success: (popup) => {
            popup.$on('cancel', () => {
              this.$popup.hide('confirm')
            })
            popup.$on('confirm', () => {
              this.$popup.hide('confirm')
              const { localStudentAnswer: formdata } = this.currentQuestion
              formdata.studentDuration = this.cumulativeTime.value // 更新做题时间
              this.cumulativeTime.reset() // 停止计时
              this.$nextTick(() => _submit())
            })
            popup.setData({
              content: '确认提交？'
            })
          }
        })
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.navBox {
  padding: 0 20px;
  box-sizing: border-box;
}
.back {
  height: 100%;
  display: flex;
  align-items: center;
  font-size: 28px;

  .icon {
    width: 17.14px;
    height: 30px;
    margin-right: 11px;
  }
}
.nav-bar-btns {
  .item {
    height: 30px;
    .icon {
      width: 22px;
      height: 22px;
    }

    .name {
      font-size: 22px;
      line-height: 22px;
    }
  }
}

.container {
  border-radius: 16px;

  .task,
  .answer {
    .module-item {
      font-size: 26px;

      .rect {
        width: 4px;
        height: 26px;
        background: linear-gradient(180deg, #51c3ff 0%, #31b3f7 100%);
        border-radius: 3px;
      }

      .title {
        font-family: 'sans-serif';
      }
    }

    .content {
      font-size: 26px;
      line-height: 28px;
      margin-top: 8px;
      word-break: break-all;
    }
    .img-content {
      margin-top: 20px;
      display: flex;
      flex-wrap: wrap;
      .img-item {
        width: 120px;
        height: 120px;
        margin-right: 20px;
        margin-bottom: 20px;
        background: #f4f7fb;
      }
    }
  }

  .upload-wrap,
  .upload-tips {
    font-size: 18px;

    .list-wrap {
      display: inline-grid;
      grid-template-columns: 131px 131px 131px 131px 131px 131px 131px 131px;
      grid-column-gap: 20px;
      grid-row-gap: 20px;

      .item {
        width: 131px;
        height: 131px;
        display: flex;
        justify-content: center;
        align-items: center;

        .photo {
          width: 131px;
          height: 131px;
        }

        .other {
          width: 60px;
          height: 60px;
        }
      }

      .delete {
        width: 24px;
        height: 24px;
        top: -12px;
        right: -12px;
      }
    }
  }
}
</style>
